package com.oa.om.ctrl;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import com.mdp.core.utils.NumberUtil;
import com.mdp.core.utils.ObjectTools;
import com.oa.om.OmTools;
import com.oa.om.entity.OmAppliance;
import com.oa.om.entity.OmAppliancePurchase;
import com.oa.om.entity.OmApplianceRequire;
import com.oa.om.service.OmAppliancePurchaseService;
import com.oa.om.service.OmApplianceRequireService;
import com.oa.om.service.OmApplianceService;
import io.swagger.v3.oas.annotations.Operation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import io.swagger.annotations.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.mdp.core.entity.Result;
import com.mdp.core.query.QueryTools;
import static com.mdp.core.utils.BaseUtils.*;
import com.mdp.core.entity.LangTips;
import com.mdp.safe.client.entity.User;
import com.mdp.safe.client.utils.LoginUtils;
import com.mdp.swagger.ApiEntityParams;

import com.oa.om.service.OmApplianceStorageService;
import com.oa.om.entity.OmApplianceStorage;
/**
 * @author 唛盟开源 code-gen
 * @since 2024-8-21
 */
@RestController
@RequestMapping(value="/oa/om/omApplianceStorage")
@Api(tags={"办公用品出入库流水表-操作接口"})
public class OmApplianceStorageController {
	
	static Logger logger =LoggerFactory.getLogger(OmApplianceStorageController.class);
	
	@Autowired
	private OmApplianceStorageService omApplianceStorageService;

    @Autowired
    private OmAppliancePurchaseService purchaseService;

    @Autowired
    private OmApplianceRequireService requireService;


    @Autowired
    private OmApplianceService applianceService;

	@Operation( summary =  "办公用品出入库流水表-查询列表")
	@ApiEntityParams(OmApplianceStorage.class)
	@RequestMapping(value="/list",method=RequestMethod.GET)
	public Result listOmApplianceStorage(  @RequestParam Map<String,Object> params){
			User user=LoginUtils.getCurrentUserInfo();
			QueryWrapper<OmApplianceStorage> qw = QueryTools.initQueryWrapper(OmApplianceStorage.class , params);
			IPage page=QueryTools.initPage(params);
			List<Map<String,Object>> datas = omApplianceStorageService.selectListMapByWhere(page,qw,params);
			return Result.ok("query-ok","查询成功").setData(datas).setTotal(page.getTotal());
	}
	

	@Operation( summary =  "办公用品出入库流水表-新增")
	@RequestMapping(value="/add",method=RequestMethod.POST)
	public Result addOmApplianceStorage(@RequestBody OmApplianceStorage omApplianceStorage) {
        User user = LoginUtils.getCurrentUserInfo();
        OmTools.validOmAdminQx();

        if(ObjectTools.isEmpty(omApplianceStorage.getNum())){
            omApplianceStorage.setNum(BigDecimal.ZERO);
        }
        if(!"1".equals(omApplianceStorage.getDirect()) && !"2".equals(omApplianceStorage.getDirect())){
            return Result.error("direct-error","请输入正确的出入方向，1-入库，2-出库");
        }
        if("2".equals(omApplianceStorage.getDirect())){//出库
            if(omApplianceStorage.getNum()==null){
                return Result.error("out-num-required","出库数量不能为空");
            }
            OmAppliance omAppliance=applianceService.getById(omApplianceStorage.getApplianceId());
            if(omAppliance==null){
                return Result.error("data-0","用品【%s】【%s】不存在",omApplianceStorage.getApplianceId(),omApplianceStorage.getApplianceName());
            }
            if(NumberUtil.lt(omAppliance.getStock(),omApplianceStorage.getNum(),2)){
                return Result.error("当前库存【%s】小于【%s】,库存不足",omAppliance.getStock().intValue(),omApplianceStorage.getNum().intValue());
            }
        }else{

            if(omApplianceStorage.getNum()==null){
                return Result.error("in-num-required","入库数量不能为空");
            }
        }
        OmAppliancePurchase purchase=null;
        if(ObjectTools.isNotEmpty(omApplianceStorage.getBillId()) && "purchase".equals(omApplianceStorage.getBillType())){//如果是根据采购单创建

            purchase=purchaseService.getById(omApplianceStorage.getBillId());
            if(purchase==null){
                return Result.error("purchase-0","采购单不存在");
            }
            if(!"2".equals(purchase.getBizFlowState())){
                return Result.error("bizFlowState-not-2","采购单【%s】不是已审核通过状态,不允许出入库操作",purchase.getId());
            }
            // 计算采购单下的入库总量是否已大于当前库存总量
            List<OmApplianceStorage> rows=omApplianceStorageService.lambdaQuery().eq(OmApplianceStorage::getBillId,omApplianceStorage.getBillId()).list();
            if(rows.size()>0){
                BigDecimal sum=OmTools.sumStock(rows);
                BigDecimal canInNum=purchase.getPurchaseNum().subtract(sum);
                if(NumberUtil.gt(omApplianceStorage.getNum(),canInNum,2)){
                    return Result.error("sum-stock-num-gt-purchase-num","采购单总量为【%s】,已入库数量为【%s】,当前可入库数量【%s】小于 【%s】",purchase.getPurchaseNum().intValue(),sum.intValue(),canInNum.intValue(),omApplianceStorage.getNum().intValue());
                };
            }
        }
        OmApplianceRequire require=null;
        if(ObjectTools.isNotEmpty(omApplianceStorage.getBillId())&& "apply_for_use".equals(omApplianceStorage.getBillType())){//如果是根据申领单创建出库单（领取），入库单（归还）

            require=requireService.getById(omApplianceStorage.getBillId());

            if(require==null){
                return Result.error("require-0","申领单不存在");
            }
            if(!"2".equals(require.getBizFlowState())){
                return Result.error("bizFlowState-not-2","申领单【%s】不是已审核通过状态,不允许出入库操作",require.getId());
            }
            // 计算采购单下的入库总量是否已大于当前库存总量
            List<OmApplianceStorage> rows=omApplianceStorageService.lambdaQuery().eq(OmApplianceStorage::getBillId,omApplianceStorage.getBillId()).list();
            if(rows.size()>0){
                BigDecimal inSum=OmTools.sumStock(rows,"1");
                BigDecimal outSum=OmTools.sumStock(rows,"2");
                BigDecimal toBackNum=outSum.subtract(inSum);
                if("1".equals(omApplianceStorage.getDirect())){//入库
                    if(NumberUtil.lt(toBackNum,omApplianceStorage.getNum(),2)){
                        return Result.error("sum-stock-num-gt-purchase-num","申领单总量为【%s】,当前待归还数量为【%s】小于 【%s】，请检查表单入库数量是否填错",require.getReqNum().intValue(),toBackNum.intValue(),omApplianceStorage.getNum().intValue());
                    };
                }else{//申领出库
                    BigDecimal canOut=require.getReqNum().subtract(outSum).add(inSum);
                    if(NumberUtil.lt(canOut,omApplianceStorage.getNum(),2)){
                        return Result.error("sum-stock-num-gt-purchase-num","申领单总量为【%s】,当前可申领数量【%s】小于 【%s】，请检查表单出库数量是否填错",require.getReqNum().intValue(),canOut.intValue(),omApplianceStorage.getNum().intValue());
                    };
                }

            }
        }
        omApplianceStorage.setLtime(new Date());
        omApplianceStorage.setCreateTime(new Date());
        omApplianceStorage.setUserid(user.getUserid());
        omApplianceStorage.setUsername(user.getUsername());
        if("2".equals(omApplianceStorage.getDirect())){
            omApplianceStorage.setFromUserid(user.getUserid());
            omApplianceStorage.setFromUsername(user.getUsername());
            if(require!=null && ObjectTools.isEmpty(omApplianceStorage.getTargetUserid())){
                omApplianceStorage.setTargetUserid(require.getUserid());
                omApplianceStorage.setTargetUsername(require.getUsername());
            }
        }else{
            omApplianceStorage.setTargetUserid(user.getUserid());
            omApplianceStorage.setTargetUsername(user.getUsername());

            if(require!=null && ObjectTools.isEmpty(omApplianceStorage.getFromUserid())){
                omApplianceStorage.setFromUserid(require.getUserid());
                omApplianceStorage.setFromUsername(require.getUsername());
            }

            if(purchase!=null && ObjectTools.isEmpty(omApplianceStorage.getFromUserid())){
                omApplianceStorage.setFromUserid(purchase.getUserid());
                omApplianceStorage.setFromUsername(purchase.getUsername());
            }

        }
		 omApplianceStorageService.save(omApplianceStorage);
        applianceService.stockTaking(omApplianceStorage.getApplianceId());
         return Result.ok("add-ok","添加成功！").setData(omApplianceStorage);
	}

	@Operation( summary =  "办公用品出入库流水表-删除")
	@RequestMapping(value="/del",method=RequestMethod.POST)
	public Result delOmApplianceStorage(@RequestBody OmApplianceStorage omApplianceStorage){
        OmTools.validOmAdminQx();
        omApplianceStorage=this.omApplianceStorageService.getById(omApplianceStorage.getId());
		omApplianceStorageService.removeById(omApplianceStorage);
        applianceService.stockTaking(omApplianceStorage.getApplianceId());
        return Result.ok("del-ok","删除成功！");
	}

	@Operation( summary =  "办公用品出入库流水表-修改")
	@RequestMapping(value="/edit",method=RequestMethod.POST)
	public Result editOmApplianceStorage(@RequestBody OmApplianceStorage omApplianceStorage) {
        OmTools.validOmAdminQx();
        OmApplianceStorage db=omApplianceStorageService.getById(omApplianceStorage.getId());
		omApplianceStorageService.updateById(omApplianceStorage);
        applianceService.stockTaking(db.getApplianceId());
        return Result.ok("edit-ok","修改成功！");
	}

    @Operation( summary =  "办公用品出入库流水表-批量修改某些字段" )
    @ApiEntityParams( value = OmApplianceStorage.class, props={ }, remark = "办公用品出入库流水表", paramType = "body" )
	@RequestMapping(value="/editSomeFields",method=RequestMethod.POST)
	public Result editSomeFields(   @RequestBody Map<String,Object> params) {
            User user= LoginUtils.getCurrentUserInfo();
        OmTools.validOmAdminQx();
        List<String> ids= (List<String>) params.get("$pks");
        List<OmApplianceStorage> dbs=omApplianceStorageService.listByIds(ids);
        for (OmApplianceStorage db : dbs) {
            OmTools.validBizFlowStateIs(params,db.getBizFlowState());
        }
            omApplianceStorageService.editSomeFields(params);
        for (OmApplianceStorage db : dbs) {
            applianceService.stockTaking(db.getApplianceId());
        }
            return Result.ok("edit-ok","更新成功");
	}

	@Operation( summary =  "办公用品出入库流水表-批量删除")
	@RequestMapping(value="/batchDel",method=RequestMethod.POST)
	public Result batchDelOmApplianceStorage(@RequestBody List<OmApplianceStorage> omApplianceStorages) {
	    User user= LoginUtils.getCurrentUserInfo();
        OmTools.validOmAdminQx();
        if(omApplianceStorages.size()<=0){
            return Result.error("batchDel-data-err-0","请上送待删除数据列表");
        }
         List<OmApplianceStorage> datasDb=omApplianceStorageService.listByIds(omApplianceStorages.stream().map(i-> i.getId() ).collect(Collectors.toList()));

        List<OmApplianceStorage> can=new ArrayList<>();
        List<OmApplianceStorage> no=new ArrayList<>();
        for (OmApplianceStorage data : datasDb) {
            if(true){
                can.add(data);
            }else{
                no.add(data);
            }
        }
        List<String> msgs=new ArrayList<>();
        if(can.size()>0){
            omApplianceStorageService.removeByIds(can);
            msgs.add(LangTips.transMsg("del-ok-num","成功删除%s条数据.",can.size()));
        }

        if(no.size()>0){
            msgs.add(LangTips.transMsg("not-allow-del-num","以下%s条数据不能删除:【%s】",no.size(),no.stream().map(i-> i.getId() ).collect(Collectors.joining(","))));
        }
        if(can.size()>0){

            for (OmApplianceStorage storage : can) {
                applianceService.stockTaking(storage.getApplianceId());
            }
             return Result.ok(msgs.stream().collect(Collectors.joining()));
        }else {
            return Result.error(msgs.stream().collect(Collectors.joining()));
        }
	} 

	@Operation( summary =  "办公用品出入库流水表-根据主键查询一条数据")
    @RequestMapping(value="/queryById",method=RequestMethod.GET)
    public Result queryById(OmApplianceStorage omApplianceStorage) {
        OmApplianceStorage data = (OmApplianceStorage) omApplianceStorageService.getById(omApplianceStorage);
        return Result.ok().setData(data);
    }

}
